import { Component, OnInit, Output, EventEmitter } from '@angular/core';

import * as formatUtil from './monitor-treemap-util';
import { MonitorService } from 'src/app/core/service/monitor.service';
import { MonitorTreeMap } from 'src/app/shared/models';
import { MockDataService } from 'src/app/core/service/mcok-data.service';

const TREEMAP_TITLE = '软件资产分析';

@Component({
  selector: 'monitor-treemap',
  templateUrl: './monitor-treemap.component.html',
  styleUrls: ['./monitor-treemap.component.scss']
})
export class MonitorTreemapComponent implements OnInit {
  // tslint:disable-next-line:prefer-output-readonly
  @Output() switchFullScreen = new EventEmitter<boolean>();

  isFullScreen = false;
  updateChartOption;
  queryName: string;
  queryValueList: Array<{ id: any, name: string }>;
  echartsInstance: any;
  currentNodeId: string;
  data = [];
  initOpts = {
    renderer: 'svg',
  };

  chartOption = {
    tooltip: {
      formatter: function (info) {
        const description = info.data.description;
        let showText;
        if (description) {
          showText = description.replace(/@@/g, '<br/>');
        } else {
          const treePathInfo = info.treePathInfo;
          const treePath = [];

          for (let i = 1; i < treePathInfo.length; i++) {
            let treeNodeName = treePathInfo[i].name;
            if (treeNodeName.indexOf('$#$warning') !== -1) {
              treeNodeName = treeNodeName.split('$#$warning')[0];
            }
            treePath.push(treeNodeName);
          }
          showText = treePath.join('/');
        }
        return [
          '<div class="tooltip-title">' + showText +
          '</div>',
        ].join('');
      }
    },

    series: [{
      name: TREEMAP_TITLE,
      type: 'treemap',
      left: '20',
      right: '20',
      bottom: '50',
      top: '20',
      leafDepth: 3,
      roam: false, // 关闭拖拽操作
      label: {
        show: true,
        formatter: '{b}',
        position: 'inside'
      },
      upperLabel: {
        normal: {
          show: false
        }
      },
      itemStyle: {
        normal: {
          borderColor: '#fff'
        }
      },
      levels: [
        {
          itemStyle: {
            normal: {
              borderWidth: 0,
              gapWidth: 5
            }
          },
          upperLabel: {
            normal: {
              show: false
            }
          }
        },
        {
          itemStyle: {
            normal: {
              borderColor: '#555',
              borderWidth: 2,
              gapWidth: 1
            }
          },
          upperLabel: {
            normal: {
              show: true,
              position: [0, 10]
            }
          }
        },
        {
          colorSaturation: [0.35, 0.5],
          itemStyle: {
            normal: {
              borderColor: '#000',
              borderWidth: 5,
              gapWidth: 1,
              borderColorSaturation: 0.6
            }
          },
          upperLabel: {
            normal: {
              show: true,
              position: [0, 10]
            }
          }
        }
      ],
      data: []
    }]
  };

  constructor(private monitorService: MonitorService,
    private mockService: MockDataService) {
    this.monitorService.getMonitorTreemap().subscribe(
      (treemap: Array<MonitorTreeMap>) => {
        treemap.forEach(treeItem => {
          if (treeItem.children.length === 2) {
            treeItem.children[1].children.forEach(libItem => {
              if (libItem.bink) {
                libItem.name += '$#$warning';
              }
            });
          }
        });
        this.data = treemap;
        this.updateChartOption = {
          series: [{
            data: this.data
          }]
        };
      }
    );
  }


  ngOnInit(): void { }

  toggleFullScreen() {
    this.isFullScreen = !this.isFullScreen;
    this.switchFullScreen.emit(this.isFullScreen);
  }

  updMonitor() {
    this.data[1].children[1].itemStyle = {
      'color': 'blue'
    };
    this.data[1].itemStyle = {
      'borderColor': 'blue'
    };
    this.updateChartOption = {
      series: [{
        data: this.data
      }]
    };
    setTimeout(() => {
      if (this.echartsInstance) {
        this.echartsInstance.dispatchAction({
          type: 'treemapZoomToNode',
          seriesName: TREEMAP_TITLE,
          targetNodeId: this.currentNodeId
        });
      }
    });
  }

  updWarning() {
    this.data[0].name += '$#$warning';
    this.data[0].children[5].name += '$#$warning';
    this.data[1].name += '$#$warning';
    this.data[1].children[5].name += '$#$warning';
    this.data[2].name += '$#$warning';
    this.data[2].children[5].name += '$#$warning';
    this.updateChartOption = {
      series: [{
        data: this.data
      }]
    };
  }



  onChartInit(e: any) {
    this.echartsInstance = e;
    console.log('on chart init:', e);
  }

  returnRoot() {
    if (this.echartsInstance) {
      this.echartsInstance.dispatchAction({
        type: 'treemapZoomToNode',
        targetNodeId: TREEMAP_TITLE
      });
    }
  }

  addDynamicData() {
    if (this.data[1].children == null) {
      this.data[1].children = [];
    }
    this.data[1].children.push({
      'value': 100,
      'name': 'commons-fileupload-1.2.7.jar',
      'id': '039'
    });
    this.updateChartOption = {
      series: [{
        data: this.data
      }]
    };

    setTimeout(() => {
      if (this.echartsInstance) {
        this.navigateNode(this.currentNodeId);
      }
    });
  }

  onChartEvent(event: any, type: string) {
    console.log('chart event:', type, event);
    if (event.nodeData && event.nodeData.dataIndex === 0) {
      this.currentNodeId = null;
    } else {
      this.currentNodeId = event.data.id;
    }
  }

  queryNodeName(nodeName) {
    // 先找精确匹配的
    let nodeIdList = this.findNodeId(nodeName, this.data);
    // 再找模糊匹配的
    if (!nodeIdList.length) {
      nodeIdList = this.findNodeId(nodeName, this.data, true);
    }

    this.queryValueList = nodeIdList;
  }

  navigateNode(nodeId) {
    this.echartsInstance.dispatchAction({
      type: 'treemapZoomToNode',
      seriesName: TREEMAP_TITLE,
      targetNodeId: nodeId
    });
  }

  private findNodeId(nodeName, originList, fuzzy?) {
    const out = [];
    nodeName = nodeName.toLowerCase();

    for (let i = 0, len = originList.length; i < len; i++) {
      const node = originList[i];
      if (node.name
        && (
          fuzzy
            ? node.name.toLowerCase().indexOf(nodeName) === 0
            : node.name.toLowerCase() === nodeName
        )
      ) {
        out.push({ id: node.id, name: node.name });
      }
      if (node.children) {
        out.push.apply(out, this.findNodeId(nodeName, node.children, fuzzy));
      }
    }
    return out;
  }

}
